<?php

$maxBlocks = 1000;
$blockDivisor = 200;
$baseBitsPerBlock = 5;
$blocksMined = getBlocksMined();

function mine() {
	global $id;

	$difficulty = getDifficulty();
	$bitsPerBlock = getBitsPerBlock();
	$bits = mineBlock($difficulty, $bitsPerBlock);

	if ($bits != 0) {
		// Add bits to account
		$balance = getUserBalance($id);
		$balance += $bits;
		setUserBalance($id, $balance);

		// Add block to blocksMined
		incrementBlocksMined();

		// Set new blockLocation
		$difficulty = getDifficulty();
		$newLocation = rand(0, pow(2, log2($difficulty)));
		setBlockLocation($newLocation);

		echo '<b><p style="color:green">SwagMoney Block Found: ' . number_format($bits, 3) . ' SwagMoneys!</p></b>';
	} else echo false;
}

function getDifficulty() {
	global $blocksMined;
	$difficultyFactor = 1.0014891847914886;
	return pow(2, 7 * pow($difficultyFactor, $blocksMined));
}

function mineBlock($difficulty, $bitsPerBlock) {
	$mineLocation = rand(0, pow(2, log2($difficulty)));
	$blockLocation = getBlockLocation();

	if ($mineLocation == $blockLocation) $blockFound = true;
	else $blockFound = false;

	if ($blockFound) return $bitsPerBlock;
	else return 0;
}

function log2($number) {
	return log($number) / log(2);
}

function getBitsPerBlock() {
	global $blocksMined, $blockDivisor, $baseBitsPerBlock;
	$val = floatval($baseBitsPerBlock) / ceil(($blocksMined + 1) / $blockDivisor);
	return $val;
}